'use strict';

const Service = require('egg').Service;

class ApprovalPermissionService extends Service {
  /**
   * 获取人员信息（包含审批审批权限）
   * @param {Object} params - 查询参数
   * @param {number} [params.person_id] - 人员ID（可选，不填则查询所有）
   * @param {number} [params.department_id] - 部门ID（可选）
   * @param {string} [params.person_name] - 人员姓名（可选，模糊查询）
   * @param {number} [params.page=1] - 页码
   * @param {number} [params.page_size=10] - 每页条数
   * @returns {Promise<Object>} 人员列表和分页信息
   */
  async getPersonnelWithPermissionsService(params) {
    const {
      person_id,
      department_id,
      person_name,
      page = 1,
      page_size = 10
    } = params;

    const offset = (page - 1) * page_size;
    const whereConditions = [];
    const queryParams = [];

    // 添加查询条件
    if (person_id) {
      whereConditions.push('p.person_id = ?');
      queryParams.push(person_id);
    }

    if (department_id) {
      whereConditions.push('p.department_id = ?');
      queryParams.push(department_id);
    }

    if (person_name) {
      whereConditions.push('p.person_name LIKE ?');
      queryParams.push(`%${person_name}%`);
    }

    // 只查询未删除且已启用的人员
    whereConditions.push('p.is_deleted = 0');
    whereConditions.push('p.is_actived = 1');

    const whereClause = whereConditions.length ?
      `WHERE ${whereConditions.join(' AND ')}` :
      '';

    // 计算总数
    const countSql = `
      SELECT COUNT(*) as total 
      FROM tb_person p
      LEFT JOIN ap_approval_permissions ap ON p.person_id = ap.person_id
      ${whereClause}
    `;

    const totalResult = await this.app.mysql.query(countSql, queryParams);
    const total = totalResult[0].total;

    // 查询数据
    const dataSql = `
      SELECT 
        p.person_id,
        p.person_name,
        p.position,
        p.department_id,
        p.phone_number,
        p.role_main,
        p.role,
        p.role_destination,
        p.role_ov,
        ap.can_approve_level1,
        ap.can_approve_level2,
        ap.can_approve_level3
      FROM tb_person p
      LEFT JOIN ap_approval_permissions ap ON p.person_id = ap.person_id
      ${whereClause}
      ORDER BY p.person_id ASC
      LIMIT ? OFFSET ?
    `;

    // 添加分页参数
    const dataParams = [...queryParams, page_size, offset];
    const result = await this.app.mysql.query(dataSql, dataParams);

    // 处理权限字段（如果没有权限记录，默认为0）
    const processedResult = result.map(item => ({
      ...item,
      can_approve_level1: item.can_approve_level1 || 0,
      can_approve_level2: item.can_approve_level2 || 0,
      can_approve_level3: item.can_approve_level3 || 0
    }));

    return {
      list: processedResult,
      pagination: {
        total,
        page: parseInt(page),
        page_size: parseInt(page_size),
        total_pages: Math.ceil(total / page_size)
      }
    };
  }

  /**
   * 更新人员的审批权限
   * @param {Object} data - 更新数据
   * @param {number} data.person_id - 人员ID
   * @param {number} [data.can_approve_level1] - 是否有一级审批权限：0-无，1-有
   * @param {number} [data.can_approve_level2] - 是否有二级审批权限：0-无，1-有
   * @param {number} [data.can_approve_level3] - 是否有三级审批权限：0-无，1-有
   * @param {number} data.operator_id - 操作人ID
   * @returns {Promise<Object>} 更新结果
   */
  async updatePersonApprovalPermissionsService(data) {
    const {
      person_id,
      can_approve_level1,
      can_approve_level2,
      can_approve_level3,
      operator_id
    } = data;

    const conn = await this.app.mysql.beginTransaction();

    try {
      // 1. 检查人员是否存在
      const personResult = await conn.query(
        'SELECT * FROM tb_person WHERE person_id = ? AND is_deleted = 0',
        [person_id]
      );

      if (!personResult.length) {
        throw new Error('人员不存在或已删除');
      }

      // 2. 检查是否已有权限记录
      const permissionResult = await conn.query(
        'SELECT * FROM ap_approval_permissions WHERE person_id = ?',
        [person_id]
      );

      const permissionData = {
        person_id,
        created_at: new Date(),
        created_by: operator_id
      };

      // 添加需要更新的权限字段
      if (can_approve_level1 !== undefined) {
        permissionData.can_approve_level1 = can_approve_level1;
      }
      if (can_approve_level2 !== undefined) {
        permissionData.can_approve_level2 = can_approve_level2;
      }
      if (can_approve_level3 !== undefined) {
        permissionData.can_approve_level3 = can_approve_level3;
      }

      let result;
      if (permissionResult.length) {
        // 更新现有记录
        result = await conn.update('ap_approval_permissions', permissionData, {
          where: {
            person_id
          }
        });
      } else {
        // 创建新记录
        result = await conn.insert('ap_approval_permissions', permissionData);
      }

      await conn.commit();

      // 返回更新后的权限信息
      return await this.getPersonApprovalPermissions(person_id);
    } catch (error) {
      await conn.rollback();
      throw error;
    }
  }

  /**
   * 获取单个人员的审批权限
   * @param {number} person_id - 人员ID
   * @returns {Promise<Object>} 审批权限信息
   */
  async getPersonApprovalPermissions(person_id) {
    const result = await this.app.mysql.query(
      `SELECT 
        p.person_id,
        p.person_name,
        ap.can_approve_level1,
        ap.can_approve_level2,
        ap.can_approve_level3
       FROM tb_person p
       LEFT JOIN ap_approval_permissions ap ON p.person_id = ap.person_id
       WHERE p.person_id = ? AND p.is_deleted = 0`,
      [person_id]
    );

    if (!result.length) {
      return null;
    }

    return {
      person_id: result[0].person_id,
      person_name: result[0].person_name,
      can_approve_level1: result[0].can_approve_level1 || 0,
      can_approve_level2: result[0].can_approve_level2 || 0,
      can_approve_level3: result[0].can_approve_level3 || 0
    };
  }

  /**
   * 根据审批级别获取人员树状结构
   * @param {Object} params - 查询参数
   * @param {number} params.can_approve_level - 审批级别：1-一级审批，2-二级审批，3-三级审批
   * @returns {Promise<Array>} 人员树状列表
   */
  async findApproversByLevelTreeService(params = {}) {
    const {
      can_approve_level
    } = params;

    // 验证参数
    if (![1, 2, 3].includes(can_approve_level)) {
      throw new Error('审批级别必须是1、2或3');
    }

    // 构建权限字段名
    const permissionField = `can_approve_level${can_approve_level}`;

    // 查询有对应审批权限的人员
    const sql1 = `
      SELECT 
        p.*,
        ap.${permissionField} as has_permission
      FROM 
        tb_person p
      LEFT JOIN 
        ap_approval_permissions ap ON p.person_id = ap.person_id
      WHERE 
        p.is_deleted = 0
        AND p.is_actived = 1
        AND (ap.${permissionField} = 1 OR ap.${permissionField} IS NULL)
    `;

    const personList = await this.app.mysql.query(sql1);

    // 查询部门列表
    const sql2 = `
      SELECT 
        *
      FROM 
        tb_department
      WHERE 
        is_deleted = 0
    `;

    const departmentList = await this.app.mysql.query(sql2);

    const result = [];

    // 构建树状结构
    departmentList.forEach(departmentItem => {
      // 查找该部门下有对应审批权限的人员
      const departmentPersons = personList.filter(personItem => {
        return personItem.department_id === departmentItem.department_id &&
          (personItem.has_permission === 1 || personItem.has_permission === undefined);
      });

      // 如果部门下没有符合条件的人员，则不添加该部门
      if (departmentPersons.length === 0) {
        return;
      }

      const treeObj = {
        title: departmentItem.department_name,
        value: `department-${departmentItem.department_id}`,
        key: `department-${departmentItem.department_id}`,
        selectable: false,
        children: []
      };

      // 添加部门下的人员
      departmentPersons.forEach(personItem => {
        treeObj.children.push({
          title: personItem.person_name,
          value: personItem.person_id,
          key: personItem.person_id,
          // 可以添加额外信息
          person_id: personItem.person_id,
          position: personItem.position,
          phone_number: personItem.phone_number,
          has_permission: personItem.has_permission === 1
        });
      });

      result.push(treeObj);
    });

    return result;
  }
}

module.exports = ApprovalPermissionService;